package com.example.shipload_e.activitys.discharge_feedback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.shipload_e.R;
import com.example.shipload_e.database_dao.DBUtil;
import com.example.shipload_e.util.SharePreferenceUtil;
import com.example.shipload_e.util.SystemDateTools;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class UploadPhotosListActivity extends Activity {
	private UploadPhotosListActivity	THISAC	             = UploadPhotosListActivity.this;
	private ProgressDialog	          progressDialog;
	private SharePreferenceUtil	      spu;
	private Button	                  appPhotoButton;
	private List<Map<String, Object>>	mData;
	private ImageButton	              beforeBt, backBt;
	/* 用来标识请求照相功能的activity */
	private static final int	      CAMERA_WITH_DATA	     = 3023;
	/* 用来标识请求gallery的activity */
	private static final int	      PHOTO_PICKED_WITH_DATA	= 3021;
	/* 拍照的照片存储位置 */
	public static final File	      PHOTO_DIR	             = new File(Environment.getExternalStorageDirectory()
	                                                                 + "/SHIPMENTE/CameraCache");
	private String	                  FileName;
	private File	                  mCurrentPhotoFile;
	private ImageView	              imageViewPhoto;
	private Bitmap	                  bm;	                                                      // 需要旋转的图片资源Bitmap
	private float	                  scaleW	             = 1;	                              // 横向缩放系数，1表示不变
	private float	                  scaleH	             = 1;	                              // 纵向缩放系数，1表示不变
	private int	                      imagePosition	         = 0;
	private TextView showPositionTv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.upload_form_edit_main);
		progressDialog = new ProgressDialog(THISAC);
		spu = new SharePreferenceUtil(THISAC);
		initView();
		initDatas();
		com.example.shipload_e.util.SysApplication.getInstance().addActivity(this);
	}

	private void initView() {
		appPhotoButton = (Button) findViewById(R.id.app_photo_button);
		appPhotoButton.setOnClickListener(ocl);
		imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
		beforeBt = (ImageButton) findViewById(R.id.before);
		backBt = (ImageButton) findViewById(R.id.back);
		beforeBt.setOnClickListener(ocl);
		backBt.setOnClickListener(ocl);
		showPositionTv = (TextView) findViewById(R.id.show_position);

	}

	private void initDatas() {
		try {
			String selectId = getIntent().hasExtra("taskId") == false ? "invalid" : getIntent()
			        .getStringExtra("taskId");
			JSONArray jdatas = DBUtil.selectPhotosInformation(THISAC, selectId);
			List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
			if(jdatas.length() > 0) {
				for(int i = 0;i < jdatas.length();i++) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					JSONObject o = new JSONObject(jdatas.getString(i));
					String taskId = o.has("ID") == false ? "" : o.getString("ID");
					String status = o.has("STATUS") == false ? "" : o.getString("STATUS");
					String respondId = o.has("RESPOND_ID") == false ? "" : o
					        .getString("RESPOND_ID");
					String fileName = o.has("FILE_NAME") == false ? "" : o.getString("FILE_NAME");
					map.put("selectId", taskId);
					map.put("selectStatus", status);
					map.put("selectRespondId", respondId);
					map.put("selectFileName", fileName);
					mapList.add(map);
					beforeBt.setVisibility(View.VISIBLE);
					backBt.setVisibility(View.VISIBLE);
				}
				mData = mapList;
				initImageViewData(mData, imagePosition);
			} else {
				beforeBt.setVisibility(View.GONE);
				backBt.setVisibility(View.GONE);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public void initImageViewData(final List<Map<String, Object>> mData,final int position) {
		for(int i = 0;i < mData.size();i++) {
			showPositionTv.setText((position+1)+"/"+mData.size());
			String filepath = mData.get(position).get("selectFileName").toString();
			File file = new File(filepath);
			if(file.exists()) {
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 2;// 图片宽高都为原来的二分之一，即图片为原来的四分之一
				Bitmap bm = BitmapFactory.decodeFile(filepath, options);
				// 将图片显示到ImageView中
				imageViewPhoto.setImageBitmap(bm);
			}
		}
	}

	private final OnClickListener	ocl	= new OnClickListener() {

		                                    @Override
		                                    public void onClick(View arg0) {
			                                    switch (arg0.getId()) {
													case R.id.app_photo_button:
														doPickPhotoAction();
														break;
													case R.id.before:
														if(imagePosition <= 0) {
															imagePosition = mData.size() - 1;
														} else {
															imagePosition = imagePosition - 1;
														}
														initImageViewData(mData, imagePosition);
														break;
													case R.id.back:
														imagePosition = imagePosition + 1;
														if(imagePosition >= (mData.size())) {
															imagePosition = 0;
														}
														initImageViewData(mData, imagePosition);
														break;
													default:
														break;
												}
											}
	                                    };

	private void doPickPhotoAction() {
		Context context = UploadPhotosListActivity.this;
		// Wrap our context to inflate list items using correct theme
		final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light);
		String cancel = "返回";
		String[] choices;
		choices = new String[2];
		choices[0] = "拍照"; // 拍照
		choices[1] = "从相册中选择"; // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices);
		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle("");
		builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog,int which) {
				dialog.dismiss();
				switch (which) {
					case 0: {
						String status = Environment.getExternalStorageState();
						if(status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
							doTakePhoto();// 用户点击了从照相机获取
						} else {
							Toast.makeText(UploadPhotosListActivity.this, "没有SD卡", Toast.LENGTH_LONG)
							        .show();
						}
						break;
					}
					case 1:
						doPickPhotoFromGallery();// 从相册中去获取
						break;
				}
			}
		});
		builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog,int which) {
				dialog.dismiss();
			}
		});

		builder.create().show();
	}

	/**
	 * 拍照获取图片
	 */
	protected void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			if(!PHOTO_DIR.exists()) {
				boolean iscreat = PHOTO_DIR.mkdirs();// 创建照片的存储目录
				if(iscreat) {
					// DeviceTool
					// .makeToast(this, "图片目录：" + PHOTO_DIR.getAbsolutePath() + "创建成功。", true);
					Toast.makeText(THISAC, "图片目录：" + PHOTO_DIR.getAbsolutePath() + "创建成功。", Toast.LENGTH_SHORT)
					        .show();
				} else {
					// DeviceTool.makeToast(this, "图片目录创建失败。", true);
					Toast.makeText(THISAC, "图片目录创建失败。", Toast.LENGTH_SHORT).show();
				}
			}
			FileName = System.currentTimeMillis() + ".jpg";
			spu.setFileName(FileName);
			mCurrentPhotoFile = new File(PHOTO_DIR, FileName);
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "photoPickerNotFoundText", Toast.LENGTH_LONG).show();
		}
	}

	public Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	/**
	 * 请求Gallery程序
	 * 从相册获取图片
	 */
	protected void doPickPhotoFromGallery() {
		try {
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "没有找到照片", Toast.LENGTH_LONG).show();
		}
	}

	// // 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setAction(Intent.ACTION_GET_CONTENT);
		return intent;
	}

	// 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
	@Override
	protected void onActivityResult(int requestCode,int resultCode,Intent data) {
		if(resultCode != RESULT_OK) {
			return;
		}
		switch (requestCode) {
			case PHOTO_PICKED_WITH_DATA:
				Uri uri = data.getData();
				imageViewPhoto.setImageURI(uri);
				FileName = getPath(this, uri);// getFileFromUri(uri).getAbsolutePath();
				left(FileName);
				break;
			case CAMERA_WITH_DATA:
				right();
				break;
			default:
				break;
		}
		savePhotoToDatasAndShowInListView();
	}

	private void savePhotoToDatasAndShowInListView() {
		if(FileName != null && !"".equals(FileName)) {
			String fpath = "";
			if(FileName.indexOf("/") == -1) {
				fpath = PHOTO_DIR.getAbsolutePath() + "/" + FileName;
			} else {
				fpath = FileName;
			}
			
			initDatas();
		} else {
			Toast.makeText(THISAC, "未选择图片", Toast.LENGTH_SHORT).show();
		}
	}

	@SuppressLint("NewApi")
	public static String getPath(final Context context,final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if(isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if(isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}

				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if(isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(Uri
				        .parse("content://downloads/public_downloads"), Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if(isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[]{split[1] };

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if("content".equalsIgnoreCase(uri.getScheme())) {

			// Return the remote address
			if(isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	// 右转事件处理,手机拍照预览
	private void right() {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		if(FileName == null || "".equals(FileName)) {
			FileName = spu.getFileName();
		}
		File f = new File(PHOTO_DIR, FileName);
		if(f.exists()) {
			// 此外，你还可以使用BitmapFactory的decodeResource方法获得一个Bitmap对象
			// 使用decodeResource方法时传入的是一个drawable的资源id
			// 还有一个decodeStream方法，这个方法传入一个图片文件的输入流即可！
			bm = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
			// 设置ImageView的显示图片
			// imageViewPhoto.setImageBitmap(bm);
		} else {
			Toast.makeText(this, "文件不存在！", Toast.LENGTH_SHORT).show();
			return;
		}
		int bmpW = bm.getWidth();
		int bmpH = bm.getHeight();
		// 设置图片放大比例
		double scale = 0.1;
		// 计算出这次要放大的比例
		scaleW = (float) (scaleW * scale);
		scaleH = (float) (scaleH * scale);
		// 产生reSize后的Bitmap对象
		// 注意这个Matirx是android.graphics包下的那个
		Matrix mt = new Matrix();
		mt.postScale(scaleW, scaleH);
		// mt.setRotate(curDegrees);
		Bitmap resizeBmp = Bitmap.createBitmap(bm, 0, 0, bmpW, bmpH, mt, true);
		imageViewPhoto.setImageBitmap(resizeBmp);
		//  尝试注释以下两句来观察内存的消耗
		bm.recycle();
		System.gc();
	}

	// 左转事件处理,手机选择图片预览
	private void left(String fileName) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 2;
		bm = BitmapFactory.decodeFile(fileName, options);
		int bmpW = bm.getWidth();
		int bmpH = bm.getHeight();
		// 设置图片放大比例
		double scale = 0.5;
		// 计算出这次要放大的比例
		scaleW = (float) (scaleW * scale);
		scaleH = (float) (scaleH * scale);
		// 产生reSize后的Bitmap对象
		// 注意这个Matirx是android.graphics包下的那个
		Matrix mt = new Matrix();
		mt.postScale(scaleW, scaleH);
		// mt.setRotate(curDegrees);
		Bitmap resizeBmp = Bitmap.createBitmap(bm, 0, 0, bmpW, bmpH, mt, true);
		imageViewPhoto.setImageBitmap(resizeBmp);
		//  尝试注释以下两句来观察内存的消耗
		bm.recycle();
		System.gc();
	}

	public static String getDataColumn(Context context,Uri uri,String selection,
	        String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = {column };

		try {
			cursor = context.getContentResolver()
			        .query(uri, projection, selection, selectionArgs, null);
			if(cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if(cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	public final class ViewHolder {
		public ImageView	imageView;
		public Button		delTransport, seeTransport;
	}

	public boolean onKeyDown(int keyCode,KeyEvent event) {

		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 这里重写返回键
			startActivity(new Intent(THISAC, DischargeFinishFormActivity.class));
			return true;
		}
		return false;

	}
}
